""" 

    legislators_in_state.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which takes a state as a parameter and returns a list of the
    senators and representatives in that state as a JSON object.

    Accepts one parameter:
        state (required) - two letter abbreviation of the state
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import wsgiref.handlers
import const

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
        
from utils import SunlightUtil, memcacheUtil, textUtil

class MainHandler(webapp.RequestHandler):

    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "state":{}}
        theState = self.request.get('state', default_value=None)

        if theState is not None:
            theState = str.upper(str(theState))
            if const.LEGISLATORS_BY_STATE.has_key(theState):
                jsonOutput["state"]["state"] = str.title(const.STATES[theState])
                for key in ["senators", "representatives"]:
                    jsonOutput["state"][key] = []
                    for legislator in const.LEGISLATORS_BY_STATE[theState][key]:
                        jsonOutput["state"][key].append({"id": legislator, "name": const.FRIENDLY_NAME[legislator]})

            else:
                jsonOutput["result"] = "error"
                jsonOutput["message"] = "our list doesn't have legislators for this area"
                
        else:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = "missing state"

                         
        self.response.out.write(simplejson.dumps(jsonOutput))

        
def main():
    application = webapp.WSGIApplication([('/fb/legislators_in_state', MainHandler)],
                                       debug=True)
    run_wsgi_app(application)
                                       

if __name__ == '__main__':
    main()
